package com.tourscool.springboot.starter.log;

import com.tourscool.springboot.starter.utils.PropertySourcesUtil;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.context.properties.bind.BindResult;
import org.springframework.boot.context.properties.bind.Bindable;
import org.springframework.boot.context.properties.bind.Binder;
import org.springframework.boot.logging.LoggingSystem;
import org.springframework.boot.logging.logback.LogbackLoggingSystem;
import org.springframework.core.env.ConfigurableEnvironment;


/**
 * @author Cedric
 * @date 2022/07/06 17:38
 * @description 日志环境注入
 */
@EnableConfigurationProperties(LogProperties.class)
public class LogEnvAdvice extends AbstractEnvironmentPostProcessor {

    @Override
    protected void onProfile(ConfigurableEnvironment environment, SpringApplication application) {
        final Binder binder = Binder.get(environment);
        final BindResult<LogProperties> bindResult = binder.bind("aop.logging", Bindable.of(LogProperties.class));
        LogProperties logProperties = new LogProperties();
        if (bindResult.isBound()) {
            logProperties = bindResult.get();
        }
        // 配置日志打印格式
        if (isLogback(application)) {
            PropertySourcesUtil.set("logging.pattern.console", logProperties.getLogbackPattern());
            PropertySourcesUtil.set("logging.pattern.file", logProperties.getLogbackPattern());
            return;
        }
        PropertySourcesUtil.set("logging.pattern.console", logProperties.getLog4jPattern());
        PropertySourcesUtil.set("logging.pattern.file", logProperties.getLog4jPattern());
    }

    /**
     * 判断是否是logback日志格式
     *
     * @param application application
     * @return
     */
    private boolean isLogback(SpringApplication application) {
        final LoggingSystem loggingSystem = LoggingSystem.get(application.getClassLoader());
        return LogbackLoggingSystem.class.equals(loggingSystem.getClass());
    }
}